<?php

class Instrumentos_model extends CI_Model {

    function __construct() {
        parent::__construct();
    }

    private $apCabId;
    private $archPesUno;
    private $archPesDos;
    private $archPesTres;

    private function creaCabecera($aplicaId, $opc) {
        $participanteId = $this->participante($this->input->post("participanteTipDoc"), $this->input->post("participanteDocumento"), '');
        $retornar = "";
        $auxSql = "";
        $auxVal = "";
        if ($opc != "") {
            $auxSql = ",`aplicaInstId1`";
            $auxVal = ",'{$this->apCabId}'";
        }
        if ($aplicaId > 0) { //edita
            $sql = "update aplicainstrumento set ";
            $sql .= "aplicaInstFecha='{$this->input->post("aplicaInstFecha$opc")}',";
            $sql .= "municipioId='{$this->input->post("txtMunicipioId")}',";
            $sql .= "direccion='{$this->input->post("txtDireccion")}',";
            $sql .= "aplicaInstParcial='{$this->input->post("hdParcial")}' where aplicaInstId = '$aplicaId'";
            $this->db->query($sql);
            $sql = "select apliDet.`aplicaInstDetRuta`,apliDet.`preguntaId`,preg.preguntaArchivo,apliDet.aplicaInstDetId,preg.preguntaBloque from aplicainstrumentodetalles apliDet 
                        left join preguntas preg on preg.`preguntaId` = apliDet.`preguntaId`
                        where apliDet.`aplicaInstId` = '$aplicaId'";
            $result = $this->db->query($sql);
            foreach ($result->result() as $row) {
                $elimina = true;
                if ($row->preguntaArchivo == "Si") {
                    if ($_FILES["{$row->preguntaId}"]["name"] != "") {
                        echo "entro elimina";
                        @unlink(RUTAARCHIVOS . "/{$row->aplicaInstDetRuta}");
                    } else {
                        switch ($row->preguntaBloque) {
                            case '0': $this->archPesUno = $row->aplicaInstDetRuta;
                                break;
                            case '1': $this->archPesDos = $row->aplicaInstDetRuta;
                                break;
                            case '2': $this->archPesTres = $row->aplicaInstDetRuta;
                                break;
                        }
                        $elimina = false;
                        echo "entro switch " . $this->archPesUno . "<br/>";
                    }
                }
                if ($elimina) {
                    $sql = "delete from aplicainstrumentodetalles where `aplicaInstDetId` = '{$row->aplicaInstDetId}'";
                    echo "<br/>$sql";
                    $this->db->query($sql);
                }
            }
            $retornar = $aplicaId;
        } else { //crea
            $sql = "insert into aplicainstrumento(`aplicaInstFecha`,aplicaInstFechaCreo,`instrumentoId`,`usuarioId`,`aplicaInstParcial`,municipioId,direccion $auxSql) values (";
            $sql .= "'{$this->input->post("aplicaInstFecha$opc")}',now(),'{$this->input->post("hdInstrumento")}','{$this->session->userdata("usuarioId")}','{$this->input->post("hdParcial")}','{$this->input->post("txtMunicipioId")}','{$this->input->post("direccion")}' $auxVal)";
            $this->db->query($sql);
            $retornar = $this->db->insert_id();
        }
        if ($opc == "")
            $this->apCabId = $retornar;
        return $retornar;
    }

    public function guardaInstrumento($preguntas) {
        /* Guarda las respuestas de todos los instrumentos aplicados */
        if (!is_int(intval($this->input->post("hdaplicaInstId"))))
            exit("No es posible procesar la aplicacion");
        $this->db->trans_start(); //inicia la transaccion
        $aplicaInstCab = "";
        $aplicaInst1 = "";
        $aplicaInst2 = "";
        $participanteId = "";
        switch ($this->input->post("hdInstrumento")) {
            case '3':
                $archPesUno = "";
                $archPesDos = "";
                $archPesTres = "";
                $valPestana = $this->input->post("hdPestana");
                $aplicaInstCab = $this->creaCabecera($this->input->post("hdaplicaInstId"), "");
                $aplicaInst1 = $this->creaCabecera($this->input->post("hdaplicaInstId1"), "2");
                $aplicaInst2 = $this->creaCabecera($this->input->post("hdaplicaInstId2"), "3");
                $aplicaInstId = $aplicaInstCab . "|" . $aplicaInst1 . "|" . $aplicaInst2;
                $partId = "";
                foreach ($preguntas->result() as $pregunta) {
                    switch ($pregunta->preguntaBloque) {
                        case '0': $partId = $aplicaInstCab;
                            break;
                        case '1': $partId = $aplicaInst1;
                            break;
                        case '2': $partId = $aplicaInst2;
                            break;
                    }
                    $prgId = $pregunta->preguntaId;
                    if ($pregunta->preguntaNivel > 1) {
                        if ($this->input->post($prgId) || $this->input->post($prgId) != "") {
                            $sql = "insert into aplicainstrumentodetalles(`preguntaId`,`aplicaInstId`,`aplicaInstDetTiene`) values(";
                            $sql .= "'$prgId',$partId,'S')";
                            $this->db->query($sql);
                            $apliInstDet = $this->db->insert_id();
                            $sql = "delete from aplicainstrumentodetallesdos where aplicaInstDetId = '$apliInstDet'";
                            $this->db->query($sql);
                            $sql = "insert into aplicainstrumentodetallesdos(`aplicaInstDetDosVarchar1`,`aplicaInstDetDosVarchar2`,`aplicaInstDetId`) select varchar1,varchar2,'$apliInstDet' from temporal where transaccion = '{$this->input->post($prgId)}'";
                            $this->db->query($sql);
                        }
                    } else if ($pregunta->preguntaArchivo == "Si") {
                        if ($_FILES["$prgId"]["name"] != "") {
                            echo "<br/>Entro en creacion<br/>";
                            $nombre_tmp = $_FILES["$prgId"]["tmp_name"];
                            $ext = strrchr($_FILES["$prgId"]["name"], '.');
                            $nombre = time() . $prgId . $ext;
                            if (!move_uploaded_file($nombre_tmp, RUTAARCHIVOS . "/$nombre"))
                                die("Error al subir el archivo");
                            $sql = "insert into aplicainstrumentodetalles(`preguntaId`,`aplicaInstDetRuta`,`aplicaInstDetTipoArchivo`,`aplicaInstId`) values(";
                            $sql .= "'$prgId','$nombre','$ext',$partId)";
                            $this->db->query($sql);
                            switch ($pregunta->preguntaBloque) {
                                case '0': $this->archPesUno = $nombre;
                                    break;
                                case '1': $this->archPesDos = $nombre;
                                    break;
                                case '2': $this->archPesTres = $nombre;
                                    break;
                            }
                        }
                    } else if ($pregunta->preguntaClase == "textarea") {
                        if ($this->input->post($prgId) || $this->input->post($prgId) != "") {
                            $sql = "insert into aplicainstrumentodetalles(`aplicaInstDetRespText`,`preguntaId`,`aplicaInstId`) values(";
                            $sql .= "'{$this->input->post($prgId)}','$prgId','$partId')";
                            $this->db->query($sql);
                        }
                    }
                } //fin foreach ($preguntas->result() as $pregunta) {
                $sql = "delete FROM grupos_focales where `aplicaInstId` = $aplicaInstCab";
                $this->db->query($sql);
                $sql = "insert into grupos_focales(`participanteId`,`aplicaInstId`) select indiceInt,'$aplicaInstCab' from temporal where transaccion = '{$this->input->post("transaccion3")}' ";
                $this->db->query($sql);
                $this->db->trans_complete();
                if ($this->db->trans_status() === FALSE) {
                    echo "error";
                    return;
                }
                $aplicaInstId .= "|" . $this->archPesUno . "|" . $this->archPesDos . "|" . $this->archPesTres;
                echo "envio " . $aplicaInstId;
                echo "<script type='text/javascript'>
                    parent.fnAsignaAplica('$aplicaInstId');
                        </script>";
                break;
            default:
                if ($this->input->post("hdaplicaInstId") > 0) { //esta editando
                    $aplicaInstId = $this->input->post("hdaplicaInstId");
                    $hdInstrumento = $this->input->post("hdInstrumento");
                    switch ($hdInstrumento) {
                        case '4':
                            $sql = "update aplicainstrumento set 
                                    aplicaInstFecha = '{$this->input->post("aplicaInstFecha")}',
                                    municipioId = '{$this->input->post("municipioUbi")}',
                                    direccion = '{$this->input->post("dirUbica")}',
                                    `aplicaInstParcial` = '{$this->input->post("hdParcial")}' where `aplicaInstId` = '$aplicaInstId'";
                            break;
                        case '5':
                            $insert = "";
                            $values = "";
                            if ($this->input->post("hdTipo") == "pais")
                                $insert = "municipio = '{$this->input->post("municipio")}',
                                            modalidad = '{$this->input->post("modalidadId")}',";
                            elseif ($this->input->post("hdTipo") == "departamento")
                                $insert = "municipioId = '{$this->input->post("municipio")}',
                                           modalidadId = '{$this->input->post("modalidadId")}',";
                            $sql = "update aplicainstrumento set 
                                        aplicaInstFecha = now(),
                                        pais = '{$this->input->post("pais")}',
                                        estado = '{$this->input->post("estado")}',
                                        $insert       
                                        telefono        = '{$this->input->post("telefono")}',
                                        email           = '{$this->input->post("email")}',
                                        `tipoEntidad` = '{$this->input->post("entidad")}',
                                        cobertura       = '{$this->input->post("cobertura")}',
                                        responsable  = '{$this->input->post("responsable")}',
                                        `fuenteFinan` = '{$this->input->post("fuenFinan")}',
                                        `aplicaInstParcial` = '{$this->input->post("hdParcial")}',
                                        `tiempoDesa` = '{$this->input->post("tiemDesarrollo")}'
                                        where `aplicaInstId` = '$aplicaInstId'";
                            break;
                        case '6':
                            $sql = "update programas set `programaInstitucion` = '{$this->input->post("entidad")}',`programaNivelFormacion` = '{$this->input->post("nivelFormacion")}' where `programaId` = '{$this->input->post("programaId")}'";
                            $this->db->query($sql);
                            $sql = "update aplicainstrumento set 
                                    programaId = '{$this->input->post("programaId")}',
                                    aplicaInstFecha = '{$this->input->post("fecImplementacion")}',
                                    responsable     = '{$this->input->post("responsable")}',
                                    email           = '{$this->input->post("email")}',
                                    telefono        = '{$this->input->post("telefono")}',
                                    aplicaPagina    = '{$this->input->post("paginaWeb")}',
                                    estado          = '{$this->input->post("implementacion")}',
                                    cobertura       = '{$this->input->post("cobertura")}',
                                    aplicaApoyoInternacional     = '{$this->input->post("apoInternacional")}',
                                    aplicaInstApoyo = '{$this->input->post("apoInterinst")}',
                                    aplicaInstParcial     = '{$this->input->post("hdParcial")}' where `aplicaInstId` = '$aplicaInstId'";
                            break;
                        case '7':
                            $sql = "update aplicainstrumento set `aplicaInstParcial` = '{$this->input->post("hdParcial")}' where `aplicaInstId` = '$aplicaInstId'";
                            break;
                        case '8':
                            $sql = "update aplicainstrumento set `aplicaInstParcial` = '{$this->input->post("hdParcial")}' where `aplicaInstId` = '$aplicaInstId'";
                            break;
                        default :
                            if ($hdInstrumento >= 9 && $hdInstrumento < 19) {
                                $sql = "update aplicainstrumento set 
                                    `aplicaInstParcial` = '{$this->input->post("hdParcial")}' ,
                                    `aplicaInvestZona` = '{$this->input->post("invZona")}' ,
                                    `modalidadId` = '{$this->input->post("hdmodadlidadId")}' 
                                    where `aplicaInstId` = '$aplicaInstId'";
                            } else {
                                $participanteId = $this->participante($this->input->post("participanteTipDoc"), $this->input->post("participanteDocumento"));
                                $sql = "update aplicainstrumento set `aplicaInstFecha` = '{$this->input->post("aplicaInstFecha")}',
                                `modalidadId` = '{$this->input->post("modalidadId")}',
                                 aplicaInstActividad = '{$this->input->post("actAgente")}',
                                 ninosTipoDiscapacidad = '{$this->input->post("ninosTipoDiscapacidad")}',
                                 `aplicaInstParcial` = '{$this->input->post("hdParcial")}',
                                 ninosDiscapacidad = '{$this->input->post("ninosDiscapacidad")}',
                                `participanteId` = '$participanteId' where `aplicaInstId` = '$aplicaInstId'";
                            }
                            break;
                    }
                    $this->db->query($sql);
                } else { //esta creando el registro
                    //pone en contexto la informacion del agente educativo
                    $sql = "select `municipioId` from agentes where `agenteId` = '{$this->input->post("hdAgente")}'";
                    $result = $this->db->query($sql)->result();
                    $hdInstrumento = $this->input->post("hdInstrumento");
                    switch ($hdInstrumento) {
                        case '4':
                            $sql = "insert into aplicainstrumento(aplicaInstFecha,`aplicaInstFechaCreo`,`instrumentoId`,`usuarioId`,departamentoId,`aplicaInstParcial`,municipioId,direccion) values(";
                            $sql .= "'{$this->input->post("aplicaInstFecha")}',now(),'{$this->input->post("hdInstrumento")}','{$this->session->userdata("usuarioId")}','{$this->session->userdata("departamentoId")}','{$this->input->post("hdParcial")}','{$this->input->post("municipioUbi")}','{$this->input->post("dirUbica")}')";
                            break;
                        case '5':
                            $insert = "";
                            $values = "";
                            if ($this->input->post("hdTipo") == "pais")
                                $insert = ",municipio,modalidad";
                            elseif ($this->input->post("hdTipo") == "departamento")
                                $insert = ",municipioId,modalidadId";
                            $values = ",'{$this->input->post("municipio")}','{$this->input->post("modalidadId")}'";
                            $sql = "insert into aplicainstrumento(`aplicaInstFecha`,`aplicaInstFechaCreo`,`instrumentoId`,`usuarioId`,pais,estado,telefono,email,`tipoEntidad`,cobertura,responsable,`fuenteFinan`,`tiempoDesa`,`aplicaInstParcial` $insert) values(";
                            $sql .= "now(),now(),'{$this->input->post("hdInstrumento")}','{$this->session->userdata("usuarioId")}','{$this->input->post("pais")}','{$this->input->post("estado")}',";
                            $sql .= "'{$this->input->post("telefono")}','{$this->input->post("email")}','{$this->input->post("entidad")}','{$this->input->post("cobertura")}','{$this->input->post("responsable")}','{$this->input->post("fuenFinan")}','{$this->input->post("tiemDesarrollo")}','{$this->input->post("hdParcial")}' $values)";
                            break;
                        case '6':
                            $sql = "update programas set `programaInstitucion` = '{$this->input->post("entidad")}',`programaNivelFormacion` = '{$this->input->post("nivelFormacion")}' where `programaId` = '{$this->input->post("programaId")}'";
                            $this->db->query($sql);
                            $sql = "insert into aplicainstrumento( `aplicaInstFechaCreo`,`programaId`,`aplicaInstFecha`,responsable,email,`instrumentoId`,`usuarioId`,telefono,`aplicaPagina`,estado,cobertura,`aplicaApoyoInternacional`,`aplicaInstApoyo`,`aplicaInstParcial`) values(";
                            $sql .= "now(),'{$this->input->post("programaId")}','{$this->input->post("fecImplementacion")}','{$this->input->post("responsable")}','{$this->input->post("email")}','{$this->input->post("hdInstrumento")}','{$this->session->userdata("usuarioId")}','{$this->input->post("telefono")}','{$this->input->post("paginaWeb")}','{$this->input->post("implementacion")}','{$this->input->post("cobertura")}','{$this->input->post("apoInternacional")}','{$this->input->post("apoInterinst")}','{$this->input->post("hdParcial")}')";
                            break;
                        case '7':
                            $sql = "insert into aplicainstrumento(`aplicaInstFechaCreo`,`instrumentoId`,`usuarioId`,departamentoId,`aplicaInstParcial`) values(";
                            $sql .= "now(),'{$this->input->post("hdInstrumento")}','{$this->session->userdata("usuarioId")}','{$this->session->userdata("departamentoId")}','{$this->input->post("hdParcial")}')";
                            break;
                        case '8':
                            $sql = "insert into aplicainstrumento(`aplicaInstFechaCreo`,`instrumentoId`,`usuarioId`,departamentoId,`aplicaInstParcial`) values(";
                            $sql .= "now(),'{$this->input->post("hdInstrumento")}','{$this->session->userdata("usuarioId")}','{$this->session->userdata("departamentoId")}','{$this->input->post("hdParcial")}')";
                            break;
                        default :
                            if ($hdInstrumento >= 9 && $hdInstrumento < 19) {
                                $sql = "insert into aplicainstrumento(`aplicaInstFechaCreo`,`instrumentoId`,`usuarioId`,departamentoId,`aplicaInstParcial`,aplicaInvestZona,`modalidadId`) values(";
                                $sql .= "now(),'{$this->input->post("hdInstrumento")}','{$this->session->userdata("usuarioId")}','{$this->session->userdata("departamentoId")}','{$this->input->post("hdParcial")}','{$this->input->post("invZona")}','{$this->input->post("hdmodadlidadId")}')";
                            } else {
                                $participanteId = $this->participante($this->input->post("participanteTipDoc"), $this->input->post("participanteDocumento"));
                                $sql = "insert into aplicainstrumento(`aplicaInstFecha`,`aplicaInstFechaCreo`,`instrumentoId`,`usuarioId`,`agenteId`,`modalidadId`,`participanteId`,`municipioId`,aplicaInstActividad,ninosDiscapacidad,ninosTipoDiscapacidad,`aplicaInstParcial`) values(";
                                $sql .= "'{$this->input->post("aplicaInstFecha")}',now(),'{$this->input->post("hdInstrumento")}','{$this->session->userdata("usuarioId")}','{$this->input->post("hdAgente")}','{$this->input->post("modalidadId")}','$participanteId','{$result[0]->municipioId}','{$this->input->post("actAgente")}','{$this->input->post("ninosDiscapacidad")}','{$this->input->post("ninosTipoDiscapacidad")}','{$this->input->post("hdParcial")}')";
                            }
                            break;
                    }
                    $this->db->query($sql);
                    $aplicaInstId = $this->db->insert_id();
                }
                //Elimino siempre cualquier contenido que exista en los detalles
                $textArea = "";
                $text = "";
                $sql = "";
                foreach ($preguntas->result() as $pregunta) {
                    $tmp = $pregunta->preguntaId;
                    if ($pregunta->preguntaArchivo == "Si") {
                        $sql = "select * from aplicainstrumentodetalles where aplicaInstId = '$aplicaInstId' and `preguntaId` = '$tmp'";
                        $result = $this->db->query($sql);
                        if ($result->num_rows() > 0 && $_FILES["$tmp"]["name"] != "") {
                            $result = $result->result();
                            @unlink(RUTAARCHIVOS . "/{$result[0]->aplicaInstDetRuta}");
                            $sql = "delete from aplicainstrumentodetalles where aplicaInstId = '$aplicaInstId' and `preguntaId` = '$tmp'";
                            $this->db->query($sql);
                        }
                        //$sql = "delete from aplicainstrumentodetalles where aplicaInstId = '$aplicaInstId' and `preguntaId` = '$tmp'";
                        if ($_FILES["$tmp"]["name"] != "") {
                            $nombre_tmp = $_FILES["$tmp"]["tmp_name"];
                            $ext = strrchr($_FILES["$tmp"]["name"], '.');
                            $nombre = time() . $ext;
                            if (!move_uploaded_file($nombre_tmp, RUTAARCHIVOS . "/$nombre"))
                                die("Error al subir el archivo");
                            $sql = "insert into aplicainstrumentodetalles(`preguntaId`,`aplicaInstDetRuta`,`aplicaInstDetTipoArchivo`,`aplicaInstId`) values(";
                            $sql .= "'$tmp','$nombre','$ext',$aplicaInstId)";
                            $this->db->query($sql);
                        }
                    }else {
                        if (!$this->input->post($tmp) || $this->input->post($tmp) == "") {
                            continue;
                        }
                        $sql = "delete from aplicainstrumentodetalles where aplicaInstId = '$aplicaInstId' and `preguntaId` = '$tmp'";
                        $this->db->query($sql);
                        $sql = "insert into aplicainstrumentodetalles(`aplicaInstDetResp`,`aplicaInstDetRespText`,`aplicaInstId`,`preguntaId`) values(";
                        if (strtolower($pregunta->preguntaClase) == "textarea") {
                            $textArea = $this->input->post($tmp);
                            $text = "";
                        } else {
                            $text = $this->input->post($tmp);
                            $textArea = "";
                        }
                        $sql .= "'$text','$textArea','$aplicaInstId','$tmp')";
                        $this->db->query($sql);
                    }
                }
                if ($this->input->post("hdInstrumento") == 4 || $this->input->post("hdInstrumento") == 18) {
                    $sql = "delete FROM grupos_focales where `aplicaInstId` = $aplicaInstId";
                    $this->db->query($sql);
                    $sql = "insert into grupos_focales(`participanteId`,`aplicaInstId`) select indiceInt,'$aplicaInstId' from temporal where transaccion = '{$this->input->post("transaccion")}' ";
                    $this->db->query($sql);
                }
                $this->db->trans_complete();
                if ($this->db->trans_status() === FALSE) {
                    echo "error";
                    return;
                }
                $aplicaInstId = $aplicaInstId . "|" . $participanteId;
                switch ($this->input->post("hdInstrumento")) {
                    case '2':
                        echo "<script type='text/javascript'>
                            parent.fnAsignaAplica('$aplicaInstId');
                                </script>";
                        break;
                    default:
                        echo $aplicaInstId;
                        break;
                }
                break;
        }
        return;
    }

//fin public function guardaInstrumento($preguntas) {
// fin public function buscaUsuario($usuario,$contra,$opc){

    public function extAgentes($usuarioId) {
        /* Extrae todos los agentes que estan relacionados a las zonas del usuario */
        $sql = "select agen.* from zonas_por_usuarios zonUsr
                inner join zonas zon on zon.`zonaId` = zonUsr.`zonaId`
                inner join departamentos dpto on dpto.`zonaId` = zon.`zonaId`
                inner join municipios mun on mun.`departamentoId` = dpto.`departamentoId`
                inner join agentes agen on agen.`municipioId` = mun.`municipioId`
                where zonUsr.`usuarioId` = '$usuarioId'";
        return $this->db->query($sql);
        return;
    }

//extAgentes

    public function agente($agenteId) {
        /* Extrae informacion del agente */
        $sql = "select * from agentes where `agenteId` = '$agenteId'";
        return $this->db->query($sql);
    }

    public function preguntas($instrumento) {
        /* Extrae todas las preguntas y posibles respuestas de una pregunta asociada a un instrumento */
        $sql = "select * from preguntas preg 
                where preg.instrumentoId = '$instrumento' order by preg.preguntaId";
        return $this->db->query($sql);
    }

    private function participante($tipDoc, $doc, $opc = "--") {
        //Crea primero el participante.
        //Verifica si existe ese participante, de existir actualiza la informacion
        $sql = "select * from participantes where `participanteTipDoc` = '$tipDoc' and `participanteDocumento` = '$doc'";
        $result = $this->db->query($sql);
        $retorna = "";
        if ($opc == "--") {
            $tmp = ($this->input->post("participanteNivelEducativo") == "Otro") ? $this->input->post("aplicaInstUltNivel_otro") : $this->input->post("participanteNivelEducativo");
            if ($result->num_rows > 0) {
                $result = $result->result();
                $retorna = $result[0]->participanteId;
                $sql = "update participantes set participanteNinosLabora = '{$this->input->post("hdninos")}',`participanteNivelEducativo` = '$tmp',`participanteNombres` = '{$this->input->post("participanteNombres")}',particiapnteEdad = '{$this->input->post("participanteEdad")}',participanteSexo = '{$this->input->post("participanteSexo")}',participanteProfesion = '{$this->input->post("participanteProfesion")}' where `participanteTipDoc` = '$tipDoc' and `participanteDocumento` = '$doc'";
                $this->db->query($sql);
            } else {
                $sql = "insert into participantes(`participanteTipDoc`,`participanteDocumento`,`participanteNombres`,`participanteSexo`,`particiapnteEdad`,`participanteProfesion`,`participanteTipo`,participanteNinosLabora,`participanteNivelEducativo`) values(";
                $sql .= "'$tipDoc','$doc','{$this->input->post("participanteNombres")}','{$this->input->post("participanteSexo")}','{$this->input->post("participanteEdad")}','{$this->input->post("participanteProfesion")}','Participante','{$this->input->post("hdninos")}','$tmp')";
                $this->db->query($sql);
                $retorna = $this->db->insert_id();
            }
        } else {
            if ($result->num_rows > 0) {
                $result = $result->result();
                $retorna = $result[0]->participanteId;
                $sql = "update participantes set participanteInstLabora = '{$this->input->post("participanteInstLabora$opc")}' where `participanteTipDoc` = '$tipDoc' and `participanteDocumento` = '$doc'";
                $this->db->query($sql);
            } else { //esta creando el participante
                $sql = "insert into participantes(`participanteTipDoc`,`participanteDocumento`,`participanteNombres`,`participanteInstLabora`,`participanteTipo`) values(";
                $sql .= "'$tipDoc','$doc','{$this->input->post("participanteNombres")}','{$this->input->post("participanteInstLabora$opc")}','Participante')";
                $this->db->query($sql);
                $retorna = $this->db->insert_id();
            }
        }
        return $retorna;
    }

    //fin private function participante($tipDoc, $doc,$opc = "") {
}

//fin class
?>
